package com.hjimi.ski.view.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.gongw.remote.communication.CommunicationKey;
import com.gongw.remote.communication.slave.CommandReceiver;
import com.gongw.remote.search.DeviceSearchResponser;
import com.hjimi.ski.R;
import com.hjimi.ski.app.MyApplication;
import com.hjimi.ski.bean.InitDeviceBean;
import com.hjimi.ski.config.Constant;
import com.hjimi.ski.iView.InitDeviceIView;
import com.hjimi.ski.presenter.InitDevicePresenter;
import com.hjimi.ski.utils.DiscoverNetIpUtil;
import com.hjimi.ski.utils.JsonParseUtil;
import com.hjimi.ski.utils.Mutils;
import com.hjimi.ski.utils.NetworkPostTask;
import com.hjimi.ski.utils.SpUtil;
import com.hjimi.ski.utils.ToastUtils;
import com.hjimi.ski.utils.update.AllDialogShowStrategy;
import com.hjimi.ski.utils.update.NotificationDownloadCreatorMandatory;
import com.hjimi.ski.utils.update.NotificationUpdateCreatorMandatory;
import com.hjimi.ski.utils.update.OkhttpCheckWorker;
import com.hjimi.ski.utils.update.OkhttpDownloadWorker;
import com.hjimi.ski.view.event.MqttDeviceInfoEvent;
import com.hjimi.ski.view.service.BindMqttService;
import com.hjimi.ski.view.widget.NoPopup;
import com.yzq.zxinglibrary.encode.CodeCreator;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.lzh.framework.updatepluginlib.UpdateBuilder;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;

/**
 * 未绑定页面
 * Created By 孙岩
 * on 2023/3/3
 */
public class UnBindActivity extends BaseActivity implements InitDeviceIView {

    private TextView tvSn;
    private LinearLayout llCode;
    private LinearLayout llSn;
    //获取是否绑定设备
    public static UnBindActivity instance = null;
    private long exitTime = 0L;
    //初始化
    private InitDevicePresenter initDevicePresenter;

    private NoPopup popup;
    private ImageView ivCode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unbind);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        instance = this;
        initViews();
        Log.d("sunyan", "mac地址===" + getMac());
        SpUtil.getInstance(UnBindActivity.this).putString(Constant.MAC, getMac());
        SpUtil.getInstance(MyApplication.getInstance().getApplicationContext()).putString("update", "");

        initDevicePresenter = new InitDevicePresenter();
        initDevicePresenter.attachView(this);

        andPermission();
    }

    //权限
    @SuppressLint("CheckResult")
    private void andPermission() {
        PermissionsUtil.requestPermission(this, new PermissionListener() {
                    @Override
                    public void permissionGranted(@NonNull String[] permissions) {
                        if (Mutils.isNetworkAvailable()) {
                            NetworkPostTask networkPostTask = new NetworkPostTask(new Handler(Looper.getMainLooper()) {
                                @Override
                                public void handleMessage(@NonNull Message msg) {
                                    switch (msg.what) {
                                        case 1:
                                            Log.d("sunyan", "" + msg.obj.toString());
                                            try {
                                                JSONObject obj = new JSONObject(msg.obj.toString());
                                                if (obj.getInt("code") == 200) {
                                                    JSONObject object = new JSONObject(obj.getString("data"));

                                                    JSONObject turnConfigObj = new JSONObject(object.getString("turn_config"));
                                                    InitDeviceBean.DataBean.TurnConfigBean turnConfigBean = new InitDeviceBean.DataBean.TurnConfigBean(
                                                            JsonParseUtil.getBoolean(turnConfigObj, "is_open"),
                                                            JsonParseUtil.getStr(turnConfigObj, "start_time"),
                                                            JsonParseUtil.getStr(turnConfigObj, "end_time"),
                                                            JsonParseUtil.getStr(turnConfigObj, "weeks")
                                                    );
                                                    JSONObject bgmConfigObj = new JSONObject(object.getString("bgm_config"));
                                                    InitDeviceBean.DataBean.BgmConfigBean bgmConfigBean = new InitDeviceBean.DataBean.BgmConfigBean(
                                                            JsonParseUtil.getBoolean(bgmConfigObj, "is_open"),
                                                            JsonParseUtil.getInt(bgmConfigObj, "bgm_id"),
                                                            JsonParseUtil.getStr(bgmConfigObj, "bgm_url"),
                                                            JsonParseUtil.getBoolean(bgmConfigObj, "is_loop")
                                                    );
                                                    InitDeviceBean.DataBean bean = new InitDeviceBean.DataBean(
                                                            JsonParseUtil.getStr(object, "mac"),
                                                            JsonParseUtil.getStr(object, "sn"),
                                                            JsonParseUtil.getInt(object, "screen_id"),
                                                            JsonParseUtil.getInt(object, "size_id"),
                                                            JsonParseUtil.getInt(object, "screen_angle_id"),
                                                            JsonParseUtil.getInt(object, "buffer_id"),
                                                            JsonParseUtil.getInt(object, "camera_angle_id"),
                                                            JsonParseUtil.getInt(object, "is_camera"),
                                                            JsonParseUtil.getStr(object, "ip"),
                                                            JsonParseUtil.getInt(object, "is_carousel"),
                                                            JsonParseUtil.getInt(object, "carousel_seconds"),
                                                            JsonParseUtil.getInt(object, "is_gesture"),
                                                            JsonParseUtil.getInt(object, "device_id"),
                                                            JsonParseUtil.getInt(object, "device_info_id"),
                                                            JsonParseUtil.getStr(object, "phone"),
                                                            JsonParseUtil.getStr(object, "token"),
                                                            turnConfigBean,
                                                            bgmConfigBean
                                                    );
                                                    showInitDevice(bean);
                                                } else if (obj.getInt("code") == 202) {
                                                    show202();
                                                } else {
                                                    ToastUtils.show(obj.getString("msg"));
                                                }

                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            break;
                                    }
                                    super.handleMessage(msg);
                                }
                            });
                            networkPostTask.execute("mac=" + SpUtil.getInstance(UnBindActivity.this).getString(Constant.MAC, "") + "&" + "sn=" + SpUtil.getInstance(UnBindActivity.this).getString(Constant.SN, "") + "&" + "ip=" + DiscoverNetIpUtil.getIpAddress(UnBindActivity.this));

                        } else {
                            //本地化部署 2023-10-11 sunyan
                            if (SpUtil.getInstance(UnBindActivity.this).getString(Constant.DEVICE_ID, "").equals("")) {

                            } else {
                                Intent intent = new Intent(UnBindActivity.this, NewImageActivity.class);
                                startActivity(intent);
                                UnBindActivity.this.finish();
                            }
                        }
                    }

                    @Override
                    public void permissionDenied(@NonNull String[] permissions) {
                        String msg = "请点击【去授权】打开相应权限！";
                        showAlert(msg);
                    }
                }, Manifest.permission.CAMERA,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    //授权
    public void showAlert(String msg) {
        new AlertDialog.Builder(this).setMessage(msg).
                setPositiveButton("去授权",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", getApplicationContext().getPackageName(), null);
                                intent.setData(uri);
                                startActivity(intent);
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).setCancelable(true).show();
    }

    //初始化控件
    private void initViews() {
        tvSn = findViewById(R.id.tvSn);
        ivCode = findViewById(R.id.ivCode);
        llCode = findViewById(R.id.llCode);
        llSn = findViewById(R.id.llSn);
    }

    //初始化判断是跳转那个页面
    private void initData(int device_info_id, int device_id) {
        if (!SpUtil.getInstance(MyApplication.getInstance().getApplicationContext()).getString("update", "1").equals("1")) {
            update();
        }
        if (device_info_id == 0) {
            //当前设备不可用或者不是系统中存在的mac地址
            showPopup("当前设备不可用");
            llCode.setVisibility(View.GONE);
            llSn.setVisibility(View.GONE);
        } else {
            llCode.setVisibility(View.VISIBLE);
            llSn.setVisibility(View.VISIBLE);
            if (device_id == 0) {
                //mqtt 小程序通过mqtt连接
                startMqttService();
                //app通过内网连接
                DeviceSearchResponser.open(this, SpUtil.getInstance(this).getInt(Constant.device_info_id, 0) + "", SpUtil.getInstance(this).getString(Constant.SN, ""));
                //开始接受通信命令
                CommandReceiver.open(new CommandReceiver.CommandListener() {
                    @Override
                    public String onReceive(final String command) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    JSONObject object = new JSONObject(command);
                                    if (object.getInt("status") == 1) {
                                        SpUtil.getInstance(UnBindActivity.this).putString(Constant.DEVICE_ID, object.getInt("id") + "");
                                        Log.d("sunyan", "编号：" + SpUtil.getInstance(UnBindActivity.this).getString(Constant.DEVICE_ID, object.getInt("id") + ""));
                                        Intent intent = new Intent(UnBindActivity.this, NewImageActivity.class);
                                        startActivity(intent);
                                        UnBindActivity.this.finish();
                                    }

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        return CommunicationKey.RESPONSE_OK +
                                "绑定成功" +
                                CommunicationKey.EOF;
                    }
                });

            } else {
                Intent intent = new Intent(UnBindActivity.this, NewImageActivity.class);
                startActivity(intent);
                UnBindActivity.this.finish();
            }
        }
    }

    private void showPopup(String msg) {
        popup = new NoPopup(this, msg);
        popup.setPopupWindowFullScreen(true);
        popup.showPopupWindow();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 判断是否在两秒之内连续点击返回键，是则退出，否则不退出
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                // 将系统当前的时间赋值给exitTime
                exitTime = System.currentTimeMillis();
            } else {
                try {
                    MyApplication.getInstance().finishManager.removeActivity(UnBindActivity.class);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                this.finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void update() {
        String mCurVersionName = Mutils.getLocalVersionName(this);
        int mCurVersionCode = Mutils.getLocalVersion(this);
        UpdateBuilder builder = UpdateBuilder.create();

        // 根据各项是否选择使用默认配置进行使用更新。
        builder.setCheckWorker(OkhttpCheckWorker.class);
        builder.setUpdateStrategy(new AllDialogShowStrategy());
        builder.setDownloadNotifier(new NotificationDownloadCreatorMandatory());
        builder.setCheckNotifier(new NotificationUpdateCreatorMandatory(builder, mCurVersionName, mCurVersionCode, new NotificationUpdateCreatorMandatory.NotificationUpdateCreatorI() {
            @Override
            public void onClick(int button) {
                if (button == 0) {

                }
            }

            @Override
            public void isNotMandatory() {//不是强制升级

            }
        }));
        builder.setDownloadWorker(OkhttpDownloadWorker.class);
        builder.check();
    }

    /*** 获取手机的MAC地址* @return String*/
    public String getMac() {
        String str = "";
        String macSerial = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();
                    break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        if (macSerial == null || "".equals(macSerial)) {
            try {
                return loadFileAsString("/sys/class/net/eth0/address").toUpperCase().substring(0, 17);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return macSerial;
    }

    public static String loadFileAsString(String fileName) throws Exception {
        FileReader reader = new FileReader(fileName);
        String text = loadReaderAsString(reader);
        reader.close();
        return text;
    }

    public static String loadReaderAsString(Reader reader) throws Exception {
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[4096];
        int readLength = reader.read(buffer);
        while (readLength >= 0) {
            builder.append(buffer, 0, readLength);
            readLength = reader.read(buffer);
        }
        return builder.toString();
    }

    //初始化回调
    @SuppressLint("SetTextI18n")
    @Override
    public void showInitDevice(InitDeviceBean.DataBean bean) {
        llCode.setVisibility(View.VISIBLE);
        llSn.setVisibility(View.VISIBLE);
        tvSn.setText("设备号：" + bean.getSn());
        createQRCode(bean.getSn());
        SpUtil.getInstance(UnBindActivity.this).putInt(Constant.device_info_id, bean.getDevice_info_id());
        SpUtil.getInstance(UnBindActivity.this).putString(Constant.MAC, bean.getMac());
        SpUtil.getInstance(UnBindActivity.this).putString(Constant.SN, bean.getSn());
        SpUtil.getInstance(UnBindActivity.this).putString(Constant.thisIp, bean.getIp());
        SpUtil.getInstance(UnBindActivity.this).putString(Constant.DEVICE_ID, bean.getDevice_id() + "");

        //内网连接
        initData(bean.getDevice_info_id(), bean.getDevice_id());
    }

    @Override
    public void show202() {
        showPopup("当前设备不可用");
        llCode.setVisibility(View.GONE);
        llSn.setVisibility(View.GONE);
    }

    private void startMqttService() {
        Intent intent = new Intent(this, BindMqttService.class);
        startService(intent);
    }

    //生成二维码
    private void createQRCode(String sn) {
        try {
            Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.jtyj_logo_icon);
            Bitmap bitmap = CodeCreator.createQRCode(sn, 400, 400, logo);
            ivCode.setImageBitmap(bitmap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //收到mqtt返回的数据
    @RequiresApi(api = Build.VERSION_CODES.O)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void dataEvent(MqttDeviceInfoEvent event) {
        //绑定设备
        Log.d("sunyan", "通过bind----mqtt绑定设备");
        andPermission();
        UnBindActivity.this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}